﻿using B.S.BasicData.Domain.Entities;
using B.S.BasicData.Infrastructure.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B.S.BasicData.Infrastructure.Implement
{
    /// <summary>
    /// 仓储的实现类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseRepository<T> : IBaseRepository<T> where T : BaseEntity
    {
        private readonly SCDbContext db;
        /// <summary>
        /// 在构造函数里注入数据库上下文
        /// </summary>
        /// <param name="db"></param>
        public BaseRepository(SCDbContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 添加方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<int> CreateAsync(T entity)
        {
           db.Set<T>().AddAsync(entity);
            return db.SaveChangesAsync();
        }
        /// <summary>
        /// 获取单个实体
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<T> GetModel(long Id)
        {
            return await db.Set<T>().FindAsync(Id);//通过上下文,根据id这个参数来查找实体并返回
        }
        /// <summary>
        /// 查询实体列表
        /// </summary>
        /// <returns></returns>
        public async Task<IQueryable<T>> Query()
        {
            return  db.Set<T>();
        }
        /// <summary>
        /// 更新单个实体(修改)
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public Task<int> UpdateAsync(T entity)
        {
            db.Set<T>().Update(entity);
            return db.SaveChangesAsync();
        }
    }
}
